import { Component, OnInit } from '@angular/core';
import { MyModalHelper } from '@core/my-modal.helper';
import { myValidNull } from '@core/util/string-utils';
import { NzMessageService } from 'ng-zorro-antd';
import { AgentService } from '@core/routes-services/agent.service';
import { AgentEditComponent } from './agent-edit/agent-edit.component';
import { AgentLevelService } from '@core/routes-services/agent-level.service';
import { AgentRechargeComponent } from './agent-recharge/agent-recharge.component';
import { DistrictService } from '@core/routes-services/district.service';
import { SetPasswordComponent } from '../../set-password/set-password.component';
import { ConfirmComponent } from '@shared/confirm/confirm.component';
import { AgentAreaComponent } from '../agent-area/agent-area.component';
import { AgentUpdateLevelComponent } from '../update-level/update-level.component';

@Component({
  selector: 'agent-list',
  templateUrl: './agent-list.component.html',
})
export class AgentListComponent implements OnInit {

  isLoading = false;
  keyword: any;
  levelId:any;
  districtId:any;
  page: any = { number: 1, size: 10, totalElements: 0, content: [] };

  levelOptions: any [] = [];
  districtOption:any [] = [];
  constructor(private message: NzMessageService,
              private agentService:AgentService,
              private agentLevelService: AgentLevelService,
              private districtService:DistrictService,
              private modalHelper: MyModalHelper) {
  }

  ngOnInit() {
    this.initLevelOptions();
    this.initDistrice();
    this.initPage();
  }

  initDistrice(){
    this.districtService.getAll().then((res) => {
      console.log(res )
      if (res.status.toString().startsWith("20")) {
        this.districtOption = res.data;
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error)
      this.isLoading = false;
    });
  }
  initLevelOptions() {
    this.isLoading = true;
    this.agentLevelService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.levelOptions = res.data.agentLevelsList;
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      this.isLoading = false;
    });
  }

  initPage() {
    this.isLoading = true;
    this.agentService.pagination(this.page, this.keyword, this.levelId,null,this.districtId).then((res) => {
      if (res.status.toString().startsWith("20")) {
        this.page = res.data;
        ++this.page.number;
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error)
      this.isLoading = false;
    });
  }

  /**
   * 搜索重置分页数据
   */
  search() {
    this.page = { number: 0, size: 10, totalElements: 0, content: [] };
    this.initPage();
  }

  changePageNo(pageNo) {
    this.page = { number: pageNo, size: 10, totalElements: 0, content: [] };
    this.initPage();
  }

  editEntity = (entity) => {
    let temp: boolean;
    temp = myValidNull(entity.id);
    const bak = {};
    Object.assign(bak, entity);
    this.modalHelper.open(AgentEditComponent, { entity: bak, levelOptions: this.levelOptions, districtOption: this.districtOption }, 500, {
      nzTitle: '渠道信息',
    }).subscribe(result => {
      if(result){
        this.message.success("新渠道商添加成功，请为其充值以激活渠道商账号！");
        temp ? this.search() : this.changePageNo(this.page.number);
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };

  agentRecharge = (entity) => {
    let temp: boolean;
    temp = myValidNull(entity.id);
    const bak = {};
    Object.assign(bak, entity);
    this.modalHelper.open(AgentRechargeComponent, { entity: bak, levelOptions: this.levelOptions }, 660, {
      nzTitle: '渠道充值',
    }).subscribe(result => {
      if(result){
        this.message.success("充值成功")
        this.changePageNo(this.page.number);
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };

  setCityArea = (entity) => {
    const bak = {};
    Object.assign(bak, entity);
    this.modalHelper.open(AgentAreaComponent, { entity: bak, levelOptions: this.levelOptions, districtOption: this.districtOption }, 600, {
      nzTitle: '设置独代区域',
    }).subscribe(result => {
      if(result){
        this.message.success("设置成功")
        this.changePageNo(this.page.number);
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };

  setPassword = (entity) => {
    let temp: boolean;
    temp = myValidNull(entity.id);
    const bak = {};
    Object.assign(bak, entity);
    this.modalHelper.open(SetPasswordComponent, { id: entity.id,businessService:this.agentService }, 560, {
      nzTitle: '为【'+entity.name+'】重置密码',
    }).subscribe(result => {
      if(result){
        this.message.success("修改成功");
        // this.changePageNo(this.page.number);
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };

  updateLevel = (entity) => {
    let temp: boolean;
    temp = myValidNull(entity.id);
    const bak = {};
    Object.assign(bak, entity);
    this.modalHelper.open(AgentUpdateLevelComponent, { entity: bak, levelOptions: this.levelOptions}, 560, {
      nzTitle: '调整等级',
    }).subscribe(result => {
      if(result){
        this.message.success("修改成功");
        // this.changePageNo(this.page.number);
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };
  upToTop = (entity) => {
    this.modalHelper.open(ConfirmComponent, {
      cancelText: '取消',
      subtitle:'您将晋升【'+entity.name+'】为市级独代，确认后，与该渠道相关的父级关系将全部删除！确定将该渠道的级别晋升为市级独代吗？' }, 560, {
      nzTitle: '温馨提醒',
    }).subscribe(result => {
      if(result){
        this.agentService.upgrade(entity.id,null).then((res)=>{
          if (res.status.toString().startsWith('20')) {
            this.message.warning("操作成功");
            this.changePageNo(this.page.number);
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
        })
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };

  delete = (data) => {
    // this.bannerService.deleteObj(data.id).then((data) => {
    //   this.search();
    //   this.message.success('删除成功');
    // }, error => console.log('删除出错，后续处理'));
  };

}
